package com.cloud.lawcase.api.provider;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import com.cloud.lawcase.common.openapi.OpenApiLawCauseSearchCriteria;

public class ExotericLawCausePageProvider {
	private static final String SELECT = "t1.*, t2.excute_type_name",
			FROM = "tc_dic_law_cause t1 left join tc_dic_law_excute_type t2 on t1.excute_type_id = t2.excute_type_id";

	public String listPage(OpenApiLawCauseSearchCriteria criteria) {
		SQL sql = new SQL().SELECT(SELECT).FROM(FROM);
		if (!StringUtils.isEmpty(criteria.getKeyWords())) {
			sql.WHERE("t1.cause_name like '%" + criteria.getKeyWords() + "%'");
		}

		if (criteria.getLawID()!=null) {
			sql.WHERE("t1.law_id = " + criteria.getLawID() );
		}
		if (null != criteria.getRegions() && criteria.getRegions().length > 0) {
			StringBuilder region = new StringBuilder();
			boolean b = false;
			for (String r : criteria.getRegions()) {
				if (b) {
					region.append(", ");
				}
				region.append("'").append(r).append("'");
				b = true;
			}
			region.append(", '000000'");
			sql.WHERE("exists (select * from tc_dic_law t2 where t1.law_id = t2.law_id and t2.law_region_id in ("
					+ region.toString() + "))");
		}
		if (criteria.getFuncUnitLevel() > 0) {
			// 职能级别
			sql.WHERE(
					"exists (select * from tc_rel_punish_unit_level t3 where t1.cause_id = t3.cause_id and t3.unit_func_level_id = "
							+ criteria.getFuncUnitLevel() + ")");
		}
		if (StringUtils.isNotEmpty(criteria.getFuncUnitType())) {
			// 职能部门
			sql.WHERE(
					"exists (select * from tc_rel_punish_unit_func t3 where t1.cause_id = t3.cause_id and t3.unit_func_type_id in ( "
							+ criteria.getFuncUnitType() + "))");
		}
		return sql.toString();

	}
}
